package com.wngbms;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TransmittableThreadLocalDemo {

    public static void main(String[] args) {

//        m1();
//        m2();
//        m3();

        Executor executor = Executors.newFixedThreadPool(3);
        // 提前创建好线程
        for (int i = 0; i < 3; i++) {
            executor.execute(() -> {
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
        threadLocal.set("win11");
        System.out.println(threadLocal.get());

        Runnable runnable = () -> {
            System.out.println(threadLocal.get()); // win11
        };

        TtlRunnable ttlRunnable = TtlRunnable.get(runnable);

        executor.execute(ttlRunnable);

    }

    private static void m3() {
        Executor executor = Executors.newFixedThreadPool(3);
        // 提前创建好线程
        for (int i = 0; i < 3; i++) {
            executor.execute(() -> {
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
        threadLocal.set("win11");
        System.out.println(threadLocal.get());

        // 复用线程
        executor.execute(() -> {
            System.out.println(threadLocal.get()); // null
        });
    }

    private static void m2() {
        Executor executor = Executors.newFixedThreadPool(3);

        TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
        threadLocal.set("win11");
        System.out.println(threadLocal.get());

        // 此时才创建线程
        executor.execute(() -> {
            System.out.println(threadLocal.get()); // win11
        });
    }

    private static void m1() {
        TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();

        threadLocal.set("win11");
        System.out.println(threadLocal.get());

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(threadLocal.get());
        }).start();

        threadLocal.set("win12");
        System.out.println(threadLocal.get());
    }

}
